package com.pmcc.core.web;

import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.service.JwtAuthenticationResponse;
import com.pmcc.utils.ResultBean;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.pmcc.core.config.security.JwtAuthenticationRequest;
import com.pmcc.core.config.security.JwtTokenUtil;
import com.pmcc.core.config.security.JwtUser;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class AuthenticationRestController {

   @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private UserDetailsService userDetailsService;
    @ApiOperation(value="统一登录接口", notes="返回的jwtToken要放在请求头当中")
    @PostMapping(value = "${jwt.route.authentication.path}")
    @ResponseBody
    public JwtAuthenticationResponse createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
        JwtAuthenticationResponse jwtAuthenticationResponse = new JwtAuthenticationResponse("error");
        // 刷新当前用户的
        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
       try{
           // 根据登录的用户名和密码封装成 authentication
           final Authentication authentication = authenticationManager.authenticate(
                   new UsernamePasswordAuthenticationToken(
                           authenticationRequest.getUsername(),
                           authenticationRequest.getPassword()
                   )
           );
           SecurityContextHolder.getContext().setAuthentication(authentication);

           final String token = jwtTokenUtil.generateToken(userDetails, device);
           String auth="";
           if(userDetails.getAuthorities().size()>0){
                auth=userDetails.getAuthorities().toArray()[0].toString();
           }

           // Return the token
           return new JwtAuthenticationResponse(token,"ok",auth,"account");
       }catch (Exception e){
           jwtAuthenticationResponse.setCurrentAuthority("guest");
           jwtAuthenticationResponse.setType("account");
          return jwtAuthenticationResponse;
       }

    }
    @ApiOperation(value="刷新token接口", notes="刷新token")
    @GetMapping(value = "${jwt.route.authentication.refresh}")
    @ResponseBody
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);
            String auth="";
            if(user.getAuthorities().size()>0){
                auth=user.getAuthorities().toArray()[0].toString();
            }
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken,"ok",auth,request.getAuthType().toString()));
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /*
     * 登录页需要重新发起一次请求。需要返回index.html
    */
    @GetMapping(value = "/login")
    public String getLoginPage() {
        return "index.html";
    }



}
